package com.oocl.servlet.action;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.activemq.Producer;
import com.oocl.activemq.factory.ProducerFactory;
import com.oocl.pojo.Application;
import com.oocl.pojo.Merchant;
import com.oocl.pojo.Protocol;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;
import com.oocl.util.HTTPConnUtil;
import com.oocl.util.ImageUtil;
@WebServlet("/regist.action")
public class RegistActionServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private final String IMG_STORE_LOCATION = "images"+File.separator;
	private final String O2O_STORE_LOCATION = System.getenv("CATALINA_HOME")
			+File.separator+"o2oFile"+File.separator+IMG_STORE_LOCATION;
	private final Integer IMG_SIZE_LIMIT = 1024*1024;
	private MerchantManager merchantManager=null;
	private Producer producer = null;
	private ObjectMapper mapper = null;
	
	private Logger logger = Logger.getLogger(RegistActionServlet.class);
    public RegistActionServlet() {
        super();
        merchantManager = MerchantManagerFactory.getInstance();
        producer = ProducerFactory.getAppProInstance();
        mapper = new ObjectMapper();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean isRun = HTTPConnUtil.isRun();
		if (!isRun) {
			logger.info("server down");
			request.getRequestDispatcher("serverDown").forward(request, response);
		}else {
			String errorMsg = "";
			String mId="",mName="",mPwd="",mIdCardImg="",mHeadImg="",mAddr="";
			Integer mStatus=0;
			byte[] idCardImgByte = null;
			byte[] headImgByte = null;
			String tempDir = System.getProperty("java.io.tmpdir");
			DiskFileItemFactory factory = new DiskFileItemFactory(100*1024, new File(tempDir));
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			//设置所有上传文件的总大小
//			upload.setSizeMax(1024*1024);
			//设置每个上传文件的大小
//			upload.setFileSizeMax(1024*1024);
			upload.setHeaderEncoding("UTF-8");
			try {
				List<FileItem> items = upload.parseRequest(request);
				for (FileItem item : items) {
					if (item.isFormField()) {
						String itemString = item.getString("UTF-8");
						switch (item.getFieldName()) {
						case "mName":
							if (itemString.equals("")){
								errorMsg = "账号不能为空";
								throw new NullPointerException();
							}else if (merchantManager.findOneMerchant(itemString)!=null) {
								errorMsg = "账号已存在";
								throw new Exception();
							}
							mName = itemString;
							UUID uuid = UUID.randomUUID(); 
							mId = uuid.toString();
							break;
						case "mPwd":
							if (itemString.equals("")){
								errorMsg = "密码不能为空";
								throw new NullPointerException();
							}else {
								mPwd=itemString;
							}
						case "m2Pwd":
							if (itemString.equals("")){
								errorMsg = "密码不能为空";
								throw new NullPointerException();
							}else if (!itemString.equals(mPwd)) {
								errorMsg = "密码不一致";
								throw new Exception();
							}
						case "mAddr":
							if (itemString.equals("")){
								errorMsg = "地址不能为空";
								throw new NullPointerException();
							}
							mAddr = itemString;
						}
					}else {
						switch (item.getFieldName()) {
						case "mIdCardImg":
							if(item.getSize()==0){
								errorMsg="请上传身份证照片";
								throw new NullPointerException();
							}else if (item.getSize()>IMG_SIZE_LIMIT) {
								errorMsg="身份照片不能大于1MB";
								throw new Exception();
							}else {
								byte[] idBuf = new byte[1024];
								InputStream idCardImgIn = item.getInputStream();
								ByteArrayOutputStream idCardImgBout = new ByteArrayOutputStream();
								//图片进数据库路径
								mIdCardImg = IMG_STORE_LOCATION+"idcard"+File.separator+mId+".jpg";
								//图片写进本地机器的路径
								String mIdCardImgPath = O2O_STORE_LOCATION+"idcard"
										+File.separator+mId+".jpg";
								OutputStream idCardImgOut = new FileOutputStream(new File(mIdCardImgPath));
								int idLine = 0;
								while((idLine=idCardImgIn.read(idBuf))!=-1){
									idCardImgOut.write(idBuf, 0, idLine);
									idCardImgBout.write(idBuf, 0, idLine);
								}
								idCardImgByte = idCardImgBout.toByteArray();
								idCardImgIn.close();
								idCardImgOut.close();
								idCardImgBout.close();
							}
							
							break;
						case "mHeadImg":
							if(item.getSize()==0){
								errorMsg="请上传头像照片";
								throw new NullPointerException();
							}else if (item.getSize()>IMG_SIZE_LIMIT) {
								errorMsg="头像照片不能大于1MB";
								throw new Exception();
							}else {
								byte[] headBuf = new byte[1024];
								InputStream headImgIn = item.getInputStream();
								ByteArrayOutputStream headImgBout = new ByteArrayOutputStream();
								mHeadImg = IMG_STORE_LOCATION+"head"+File.separator+mId+".jpg";
								String mHeadImgPath = O2O_STORE_LOCATION+"head"
										+File.separator+mId+".jpg";
								OutputStream headImgOut = new FileOutputStream(new File(mHeadImgPath));
								int headLine = 0;
								while((headLine=headImgIn.read(headBuf))!=-1){
									headImgOut.write(headBuf, 0, headLine);
									headImgBout.write(headBuf, 0, headLine);
								}
								headImgByte = headImgBout.toByteArray();
								headImgIn.close();
								headImgOut.close();
								headImgBout.close();
							}
							
							break;
						}
					}
				}
				//注册信息无误，无异常抛出
				Merchant merchant = new Merchant(mId, mName, mPwd, mIdCardImg, mHeadImg, mAddr, mStatus);
				String mIdCardBase64 = ImageUtil.imgByteToBase(idCardImgByte);
				String mHeadBase64 = ImageUtil.imgByteToBase(headImgByte);
				logger.info("mHeadBase64:"+mHeadBase64);
				Application application = new Application(mId, mName, mIdCardBase64, mHeadBase64, mAddr, mStatus, false, null);
				Protocol protocol = new Protocol(application);
				String json="";
				try {
					json = mapper.writeValueAsString(protocol);
				} catch (JsonProcessingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (producer.getJMSConnection()==null) {
					logger.info("connection no null");
					request.getRequestDispatcher("serverDown").forward(request, response);
				}
				producer.sendMsgToJMS(json);
				if (merchantManager.addMerchant(merchant)==0) {
					
				}
				request.setAttribute("merchant", merchant);
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
			
			catch (NullPointerException e) {
				showErrorMsg(request,response,errorMsg);	
				e.printStackTrace();
			} catch (FileUploadException e) {
				e.printStackTrace();
			}catch (Exception e) {
				showErrorMsg(request,response,errorMsg);
				e.printStackTrace();
			}finally{
				errorMsg="";
			}
		}
		
		
		
		
		
	}
	
	private void showErrorMsg(HttpServletRequest request,HttpServletResponse response,String errorMsg){
		request.setAttribute("errorMsg", errorMsg);
		try {
			request.getRequestDispatcher("WEB-INF/views/regist.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
